const mongoose = require('mongoose')
const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const secret = 'secret' // 令牌的盐
const app = new Router()

app.post('/delgoods', async (ctx) => {
  const body = ctx.request.body
  const phone = ctx.session.phone
  const table = mongoose.model('bee')
  let delgoods = null
  try {
    const tableBody = await table.findOne({ phone })
    delgoods = tableBody.delgoods.concat(body)
    await table.findOneAndUpdate({ phone }, { delgoods }, { useFindAndModify: false })
  } catch (err) {
    ctx.body = {
      code: 400,
      msg: '失败了'
    }
  }
  ctx.body = {
    code: 200,
    msg: '成功',
    delgoods
  }
})
// 该请求需携带toKen
app.post('/pay', async (ctx) => {
  const token = ctx.request.headers.token
  const table = mongoose.model('bee')
  const pwd = ctx.request.body.pwd
  const isDetail = ctx.request.body.isDetail
  const phone = ctx.session.phone
  const goods = ctx.request.body.goods
  const totalPrice = ctx.request.body.totalPrice
  await jwt.verify(token, secret, async (err) => {
    if (!err) {
      try {
        const user = await table.findOne({ phone })
        // 密码正确将商品信息添加到待收货信息里 同时将待付款里的响应信息删除
        if (user.paypwd == pwd) {
          // 更新余额
          if (user.balance >= totalPrice) {
            const newBalance = user.balance - totalPrice
            await table.findOneAndUpdate({ phone }, { balance: newBalance }, { useFindAndModify: false })
          } else {
            ctx.body = {
              code: 402,
              msg: '余额不足'
            }
          }
          // 将信息添加到待收货信息里
          // console.log(goods, user.takgoods)
          // 同时需将 status状态改为tak
          goods.map(item => {
            item.status = 'tak'
          })
          const takgoods = user.takgoods.concat(goods)
          // console.log(takgoods)
          await table.findOneAndUpdate({ phone }, { takgoods }, { useFindAndModify: false })
          // 删除待付款里的信息
          const newDelgoods = user.delgoods.filter(item => {
            for (const ii of goods) {
              if (item.orderNumber == ii.orderNumber) {
                return false
              }
            }
            return true
          })
          // 更新待付款
          await table.findOneAndUpdate({ phone }, { delgoods: newDelgoods }, { useFindAndModify: false })
          // 判断需不需要删除购物车
          if (!isDetail) {
            const newCartList = user.cartList.filter(item => {
              for (const ii of goods) {
                if (item.iid == ii.iid) {
                  return false
                }
              }
              return true
            })
            // 更新购物车
            await table.findOneAndUpdate({ phone }, { cartList: newCartList }, { useFindAndModify: false })
            ctx.body = {
              code: 200,
              msg: '付款成功'
            }
          } else {
            ctx.body = {
              code: 200,
              msg: '付款成功'
            }
          }
        } else {
          ctx.body = {
            code: 401,
            msg: '支付密码错误'
          }
        }
      } catch (err) {
        ctx.body = {
          code: 500,
          msg: '服务器错误'
        }
      }
      // ctx.body = {
      //   code: 200,
      //   msg: 'test'
      // }
    } else {
      console.log(err)
      ctx.body = {
        code: 400,
        msg: '未知错误'
      }
    }
  })
})
app.post('/confirmtak', async (ctx) => {
  const body = ctx.request.body
  const phone = ctx.session.phone
  const table = mongoose.model('bee')
  // 做两个事,第一个将该条数据添加到waitgoods里即已完成的数据里 第二个将该条数据从待收货数据里删除
  // 利用orderNumber
  try {
    await table.findOneAndUpdate({ phone }, { $push: { waitPaygoods: body } }, { useFindAndModify: false })
    await table.updateOne({ phone }, { $pull: { takgoods: { orderNumber: body.orderNumber } } }, { useFindAndModify: false })
    ctx.body = {
      code: 200,
      msg: '成功'
    }
  } catch (err) {
    ctx.body = {
      code: 500,
      msg: '失败了'
    }
  }
})

module.exports = app
